// Project name:JavaRedis
// Creator:muhong
// Date time:2022/12/8,10:04 下午
// Name:AbstractNioMessageChannel

package org.gmh.channel.nio;

import org.gmh.channel.Channel;

import java.net.SocketAddress;
import java.nio.channels.SelectableChannel;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractNioMessageChannel extends AbstractNioChannel {

    protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
        super(parent, ch, readInterestOp);
    }

    protected abstract int doReadMessages(List<Object> buf) throws Exception;

    @Override
    protected AbstractUnsafe newUnsafe() {
        return new NioMessageUnsafe();
    }

    @Override
    protected void doWrite(Object msg) throws Exception {

    }

    @Override
    protected void doClose() throws Exception {

    }

    private final class NioMessageUnsafe extends AbstractNioUnsafe {

        private final List<Object> readBuf = new ArrayList<>();

        @Override
        public void bind(SocketAddress socketAddress) {

        }

        @Override
        public void read() {
            try {
                int localRead = doReadMessages(readBuf);
                if (localRead == 0) {
                    return;
                }
                int size = readBuf.size();
                // 调用pipeline（Server的）注册到EventLoop中
                for (Object o : readBuf) {
                    pipeline().fireChannelRead(o);
                }
                //
                readBuf.clear();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
